package sz.szsmk.citizencard.ui.activity;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.Bundle;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.view.View;
import android.widget.ExpandableListView;

import com.chenenyu.router.annotation.Route;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.RealTimeLineViewBinding;
import sz.szsmk.citizencard.dialog.SuccessDialog;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.model.network.bean.response.BaseBean;
import sz.szsmk.citizencard.model.network.bean.response.QueryBusRouteRes;
import sz.szsmk.citizencard.model.network.bean.response.TestBean;
import sz.szsmk.citizencard.mvp.contract.IRealTimeLineContract;
import sz.szsmk.citizencard.mvp.presenter.RealTimePresenter;
import sz.szsmk.citizencard.ui.adapter.IndicatorExpandableListAdapter;
import sz.szsmk.citizencard.ui.adapter.OnGroupExpandedListener;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.util.JumpUtils;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/11/21 9:14
 * description:实时路线
 */
@Route("RealTimeLineActivity")
public class RealTimeLineActivity extends IBaseActivity<RealTimePresenter, RealTimeLineViewBinding>
        implements IRealTimeLineContract.IRealTimeLineView {

    private ExpandableListView expandableList;
    private IndicatorExpandableListAdapter adapter;
    private List<QueryBusRouteRes.BusRouteListBean> busRouteList = new ArrayList<>();
    private String line_name;
    private String line_guid;
    private int bus_line_collection;
    private SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected int attachLayoutRes() {
        return R.layout.real_time_line_view;
    }

    @Override
    protected void initInjector() {
        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void initViews() {
        dataBinding.titleLayout.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        line_guid = getIntent().getStringExtra("line_guid");
        line_name = getIntent().getStringExtra("line_name");
        showLoadingDialog();
        mPresenter.getRealLineData(line_guid, line_name);
        dataBinding.titleLayout.settingTitle.setText(line_name + "");
        expandableList = dataBinding.expandableList;
        swipeRefreshLayout = dataBinding.swipeRefreshLayout;
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.getRealLineData(line_guid, line_name);
            }
        });
        dataBinding.realTimeMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bus_line_collection == 0) {
                    showLoadingDialog();
                    mPresenter.addCollec(line_guid, line_name);
                } else {
                    showLoadingDialog();
                    mPresenter.cancelCollec(line_guid, line_name);
                }
            }
        });

        String json = getJson(this, "test.json");
        TestBean testBean = new Gson().fromJson(json, TestBean.class);
        List<TestBean.LineListBean> line_list = testBean.getLine_list();
        adapter = new IndicatorExpandableListAdapter(line_list, line_list);

        expandableList.setAdapter(adapter);
        adapter.setOnGroupExpandedListener(new OnGroupExpandedListener() {
            @Override
            public void onGroupExpanded(int groupPosition) {
                expandOnlyOne(groupPosition);
            }
        });

        //  设置分组项的点击监听事件
        expandableList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
//                Log.d(TAG, "onGroupClick: groupPosition:" + groupPosition + ", id:" + id);
                // 请务必返回 false，否则分组不会展开
                return true;
            }
        });
        adapter.setOnZdClickListener(new IndicatorExpandableListAdapter.OnZdClickListener() {
            @Override
            public void onZdClick(int poisiton) {
                Bundle bundle = new Bundle();
                bundle.putString("stand_name", busRouteList.get(poisiton).getBus_route_stand());
                bundle.putString("stand_guid", busRouteList.get(poisiton).getBus_route_stand());
                JumpUtils.jumptoNatvie(RealTimeLineActivity.this, "BusSiteDetailActivity", 0, bundle);
            }
        });
        //  设置子选项点击监听事件
        expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
//                Toast.makeText(NormalExpandActivity.this, Constant.FIGURES[groupPosition][childPosition], Toast.LENGTH_SHORT).show();
                return true;
            }
        });
        expandableList.setGroupIndicator(null);
        expandableList.setDivider(null);

    }

    // 每次展开一个分组后，关闭其他的分组
    private boolean expandOnlyOne(int expandedPosition) {
        boolean result = true;
        int groupLength = expandableList.getExpandableListAdapter().getGroupCount();
        for (int i = 0; i < groupLength; i++) {
            if (i != expandedPosition && expandableList.isGroupExpanded(i)) {
                result &= expandableList.collapseGroup(i);
            }
        }
        return result;
    }

    public static String getJson(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        //获得assets资源管理器
        AssetManager assetManager = context.getAssets();
        //使用IO流读取json文件内容
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName), "utf-8"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void getRealLineDataFail() {
        dismissLoadingDialog();
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    @Override
    public void getRealLineDataSucc(QueryBusRouteRes response) {
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
        dismissLoadingDialog();
        busRouteList = response.getBusRouteList();
        dataBinding.realTimeEnd.setText(response.getBus_last_time());
        dataBinding.realTimeStart.setText(response.getBus_start_time());
        dataBinding.realTimeSite.setText(response.getBus_strart_stand() + "-" + response.getBus_end_stand());
        bus_line_collection = response.getBus_line_collection();
        setStartView(bus_line_collection);
        adapter.setViewData(busRouteList);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void addCollecFail(BaseBean response) {
        bus_line_collection = 0;
        setStartView(bus_line_collection);
        dataBinding.busCb.setChecked(false);
        dismissLoadingDialog();
        final SuccessDialog dialog = new SuccessDialog(this, response.getMessage());
        dialog.show();
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                dialog.cancel();
            }
        }.start();
//        dismissLoadingDialog();
    }

    private void setStartView(int bus_line_collection) {
        if (bus_line_collection == 0) {
            dataBinding.busCb.setChecked(false);
            dataBinding.realTimeMore.setImageResource(R.drawable.icon_star_grey);
        } else {
            dataBinding.busCb.setChecked(true);
            dataBinding.realTimeMore.setImageResource(R.drawable.start_huang);
        }
    }

    @Override
    public void addCollecSucc(BaseBean response) {
        dataBinding.busCb.setChecked(true);
        dismissLoadingDialog();
        bus_line_collection = 1;
        setStartView(bus_line_collection);
        final SuccessDialog dialog = new SuccessDialog(this, response.getMessage());
        dialog.show();
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                dialog.cancel();
            }
        }.start();
//        dismissLoadingDialog();
    }

    @Override
    public void cancelCollecFail(BaseBean response) {
        dismissLoadingDialog();

        bus_line_collection = 1;
        setStartView(bus_line_collection);
        final SuccessDialog dialog = new SuccessDialog(this, response.getMessage());
        dialog.show();
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                dialog.cancel();
            }
        }.start();
        dataBinding.busCb.setChecked(true);
//        dismissLoadingDialog();
    }

    @Override
    public void cancelCollecSucc(BaseBean response) {
        dataBinding.busCb.setChecked(false);
        dismissLoadingDialog();

        bus_line_collection = 0;
        setStartView(bus_line_collection);
        final SuccessDialog dialog = new SuccessDialog(this, response.getMessage());
        dialog.show();
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                dialog.cancel();
            }
        }.start();
//        dismissLoadingDialog();
    }
}
